package com.woniuxy.happylife.service.impl;

import com.sun.org.apache.xpath.internal.operations.Bool;
import com.woniuxy.happylife.dao.RbacMenuDao;
import com.woniuxy.happylife.dao.RbacRoleDao;
import com.woniuxy.happylife.dto.AddRoleEntity;
import com.woniuxy.happylife.entity.RbacRole;
import com.woniuxy.happylife.entity.RbacRoleMenu;
import com.woniuxy.happylife.service.RbacRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname RbacRoleServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/2/17 15:08
 * @Created by hang
 */
@Service
public class RbacRoleServiceImpl implements RbacRoleService {
    @Resource
    RbacRoleDao rbacRoleDao;

    @Resource
    RbacMenuDao rbacMenuDao;
    @Override
    public List<RbacRole> findAll() {
       List<RbacRole> roles =  rbacRoleDao.findAll();
        return roles;
    }

    @Override
    public int addOne(AddRoleEntity addRoleEntity) {
        rbacRoleDao.addOne(addRoleEntity.getName());
      RbacRole rbacRole =  rbacRoleDao.findByName(addRoleEntity.getName());
      if (rbacRole == null){
          //role表中加角色
          rbacRoleDao.addOne(addRoleEntity.getName());
            //找新创建的角色id
          int newRoleId = rbacRoleDao.findIdByName(addRoleEntity.getName());
          //rolemenu表中加菜单权限
          //将传过来的menu名字表转换乘menu的id表
          List<Integer> menuIds = rbacMenuDao.findByMenuNames((List<String>) addRoleEntity.getData());
          //将roleid和所有menuid获取到list中
          List<RbacRoleMenu> addlist = new ArrayList<>();
          for (Integer i: menuIds) {
              RbacRoleMenu rbacRoleMenu = new RbacRoleMenu();
              rbacRoleMenu.setRoleid(newRoleId);
              rbacRoleMenu.setMenuid(i);
              addlist.add(rbacRoleMenu);
          }
          return rbacMenuDao.addByRoleMenus(addlist);

      }
        return 0;
    }

    @Override
    public int findById(RbacRole rbacRole) {
       int i = rbacRoleDao.findById(rbacRole);
        return i;
    }

    @Override
    public Boolean updateOne(RbacRole rbacRole) {
       Boolean success = rbacRoleDao.updateOne(rbacRole);
       if (success){
           return true;
       }
        return false;
    }
    @Override
    public Boolean deleteOneById(int id) {
      Boolean delete = rbacRoleDao.deleteOneById(id);
        if (delete){
            return true;
        }
        return false;
    }
}
